<!-- 故障诊断详情表-离线导出-->

<template>
    <!-- 报表检索条件组件 -->
    <ReportSearch :loading="loading" :searchFormDatas="searchFormDatas" v-model:searchForm="searchForm"
        @handleSearchForm="handleSearchForm" @handleResetForm="handleResetForm" />
    <!-- 报表表格组件-->
    <ReportTable :loading="loading" :tableData="tableData" :pageInfo="pageInfo"
        :summaryData="summaryData" :tableColumnData="tableColumnData" :tableColumnWidthData="tableColumnWidthData">
        <el-table-column :resizable="false" label="导出状态" prop="vehicleNumber">
			<template #default="scope">
				<span :class="`exportSpan-${scope.row.exportStatus}`"></span>
					{{ getExportStatus(scope.row.exportStatus) || '--' }}
				</template>
			</el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
                <span v-show="!scope.row.exportUrl">--</span>
				<a class="download" v-show="scope.row.exportUrl" :href="scope.row.exportUrl">下载</a>
            </template>
        </el-table-column>
    </ReportTable>
    <!-- 报表表格分页组件-->
    <ReportTablePage v-model:pageInfo="pageInfo" @handleSearchForm="handleSearchForm" />
</template>

<script setup>
import { ref, reactive, watch, onMounted, nextTick } from 'vue';

import ReportSearch from '@/components/reportSearch/index.vue';
import ReportTable from '@/components/reportTable/index.vue';
import ReportTablePage from '@/components/reportTablePage/index.vue';

import * as local from '@/utils/cache/localStorage';
import * as server from '@/api/modules/technicalDataAnalysis';
import * as basicServer from '@/api/modules/common';

import { getYesterday } from '@/utils/date';
import { apiFn, deepCopy } from '@/utils/utilFns';

const props = defineProps({
    isAddTask: {
        type: Boolean,
        required: true
    },
    queryParams: {
        type: Object,
        default: () => {}
    }
}); 

// 报表表格标题
const defaultTitle = '事件统计分析';
const tableTitle = ref(defaultTitle);

// 默认表单数据
const defaultSearchForm = {
    orgIds: local.getItem('defaultOrgIds'),
    timeFrame: [`${getYesterday(0)} 00:00:00`, `${getYesterday(0)} 23:59:59`],
    vehicleNumber: []
};

// 默认分页数据
const defaultPageInfo = {
    currentPage: 1,
    pageSize: 20,
    total: 0
};

// 加载状态
const loading = ref(false);

// 表头数据
const tableColumnData = ref([
    {
        prop: 'createUser',
        label: '创建人'
    }, {
        prop: 'createTime',
        label: '创建时间'
    }, {
        prop: 'exportStartTime',
        label: '开始时间'
    }, {
        prop: 'exportEndTime',
        label: '结束时间'
    }
]);

// 表格数据
const tableData = ref([]);

// 表头宽度数据
const tableColumnWidthData = {
    takeoverTime: '150',
};

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'selectTree',
        label: '所属组织',
        prop: 'orgIds',
        options: [],
        api: () => { },
        placeholder: '请选择所属组织',
        rules: [{ required: true, message: '请选择所属组织', trigger: ['blur, change'] }]
    },
    {
        id: 1,
        type: 'dateTimeRangePicker',
        prop: 'timeFrame',
        label: '时间范围',
        options: [],
        api: () => { },
        placeholder: '请选择时间范围',
        rules: [{ required: true, message: '请选择时间范围', trigger: ['change'] }]
    }
]);

// 表单数据
const searchForm = reactive(deepCopy(defaultSearchForm));

// 分页数据
const pageInfo = reactive(deepCopy(defaultPageInfo));

// 汇总数据
const summaryData = ref({});

onMounted(() => {
    initSearchForm();
});

// 所属组织变化监听
watch(() => searchForm.orgIds, () => {
    searchForm.vehicleNumber = [];
});

watch(() => props.isAddTask, () => {
    initSearchForm();
});

// 初始化查询参数
const initSearchForm = async() => {
    if(!Object.hasOwn(props.queryParams, 'equal')) return;
    
    const keys = Object.keys(props.queryParams['equal']);
    
    if(keys.length > 0){
        const { orgId } = props.queryParams['equal'];
        searchForm['orgIds'] = orgId;
        searchForm['timeFrame'] = [`${getYesterday(0)} 00:00:00`, `${getYesterday(0)} 23:59:59`];
        
        await nextTick();
        handleSearchForm('search');
    }
};

// 获取导出状态
const getExportStatus = (status) => {
	const statusMap = {
		'1': '导出中',
		'2': '导出失败',
		'3': '导出成功',
		'0': '无数据'
	};

	if (statusMap[status]) {
		return statusMap[status];
	} else {
		return '--';
	}
};

// 获取查询参数
const getParams = () => {
    const { orgIds, timeFrame } = searchForm;
    const { pageSize, currentPage } = pageInfo;

    const params = {
        equal: {
            orgId: orgIds,
            startTime: timeFrame[0],
			endTime: timeFrame[1],
        },
        limit: pageSize,
        page: currentPage,
    };

    return params;
};

// 获取报表列表内容
const getTableList = () => {
    const params = getParams();
    loading.value = true;
    apiFn(server.getFaultDetailExportList, params)
        .then(res => {
            const { code, data, recordsTotal } = res;
            if (code === '200') {
                if (data.length > 0) {
                    tableData.value = data;
                } 

                pageInfo.total = recordsTotal;
            }
        }).catch(() => {
            tableData.value = [];
            pageInfo.total = 0;
        }).finally(() => {
            loading.value = false;
        })
};

// 查询
const handleSearchForm = (type) => {
    if (loading.value) return;

    if (type === 'search') {
        Object.keys(defaultPageInfo).forEach(key => {
            if (key in pageInfo) {
                pageInfo[key] = defaultPageInfo[key];
            }
        })
    }
    getTableList();
};

// 重置
const handleResetForm = () => {
    Object.keys(searchForm).forEach(key => {
        if (key in defaultSearchForm) {
            searchForm[key] = defaultSearchForm[key];
        }
    });

    Object.keys(defaultPageInfo).forEach(key => {
        if (key in pageInfo) {
            pageInfo[key] = defaultPageInfo[key];
        }
    });

    tableTitle.value = defaultTitle;
    tableData.value = [];
};
</script>

<style lang="scss" scoped></style>